package com.myBlog.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myBlog.pojo.Article;
import com.myBlog.pojo.UserArticle;
import com.myBlog.services.Article.ArticleService;
import com.myBlog.services.Article.ArticleCaches;
import com.myBlog.services.Article.UserArticleService;
import com.myBlog.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserArticleService userArticleService;

    @Autowired
    private ArticleCaches articleCaches;

    // 文章分类列表
    @RequestMapping("/user/article/type")
    public JSONObject getArticleListTyped(@RequestBody JSONObject params){
        JSONObject result = new JSONObject();
        if(params.get("current")==null){
            params.put("current",1);
        }
        if(params.get("pageSize")==null){
            params.put("pageSize",10);
        }
        if( StringUtils.isEmpty( params.getString("type") )){
            params.put("type","all");
        }

        Page<UserArticle> pageData = articleCaches.getCache( params.getInteger("current"), params.getInteger("pageSize"), params.getString("type") );

        result.put("success",true);
        result.put("current", pageData.getCurrent());
        result.put("data", pageData.getRecords());
        result.put("size",pageData.getSize());
        result.put("total",pageData.getTotal());

        return result;
    }

    //查询已上线的文章列表
    public JSONObject getArticleListAuth(@RequestBody JSONObject params){
        JSONObject result = new JSONObject();
        if(params.get("current")==null){
            params.put("current",1);
        }
        if(params.get("pageSize")==null){
            params.put("pageSize",10);
        }

        Page<Article> page = new Page( params.getInteger("current"), params.getInteger("pageSize") );
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        if(params.getInteger("articleId")!= null){
            wrapper.eq(Article::getArticleId, params.getInteger("articleId"));
        }
        if(!StringUtils.isEmpty((String) params.get("contentType"))){
            wrapper.eq(Article::getContentType, params.get("contentType"));
        }
        if(!StringUtils.isEmpty((String) params.get("title"))){
            wrapper.eq(Article::getTitle, params.get("title"));
        }
        if(!StringUtils.isEmpty((String) params.get("content"))){
            wrapper.eq(Article::getContent, params.get("content"));
        }
        if(!StringUtils.isEmpty((String) params.get("type"))){
            wrapper.eq(Article::getType, params.get("type"));
        }
        if(!StringUtils.isEmpty((String) params.get("tags"))){
            String[] tags = ((String) params.get("tags")).split(",");
            Arrays.sort(tags);
            wrapper.like(Article::getTags, String.join( ",",tags));
        }
        wrapper.eq(Article::getStatus,"1");

        wrapper.orderByDesc(Article::getReleaseTime);
        Page<Article> pageData = articleService.page(page,wrapper);

        result.put("success",true);
        result.put("data", pageData.getRecords());
        result.put("size",pageData.getSize());
        result.put("total",pageData.getTotal());

        return result;
    }

    // 根据articleId查询文章
    @RequestMapping("/user/article/query")
    public JSONObject getArticleOneByID(@RequestBody JSONObject params){
        JSONObject result = new JSONObject();
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        if( params.getInteger("articleId")!= null ){
            wrapper.eq(Article::getArticleId, params.getInteger("articleId"));
        }else {
            result.put("success",false);
            result.put("data", null);
            result.put("status",0);
            result.put("info","文章id不存在");
            return result;
        }

        wrapper.eq(Article::getStatus,"1");
        wrapper.orderByDesc(Article::getReleaseTime);
        Article article = articleService.getOne(wrapper);

        result.put("success",true);
        result.put("data", article);
        result.put("status",1);

        return result;
    }

    //查询全部的文章列表
    @RequestMapping("/admin/article/query")
    public JSONObject getArticleList(@RequestBody JSONObject params){
        JSONObject result = new JSONObject();
        if(params.get("current")==null){
            params.put("current",1);
        }
        if(params.get("pageSize")==null){
            params.put("pageSize",10);
        }

        Page<Article> page = new Page( params.getInteger("current"), params.getInteger("pageSize") );
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty((String) params.get("articleId"))){
            wrapper.eq(Article::getArticleId, params.get("articleId"));
        }
        if(!StringUtils.isEmpty((String) params.get("contentType"))){
            wrapper.eq(Article::getContentType, params.get("contentType"));
        }
        if(!StringUtils.isEmpty((String) params.get("title"))){
            wrapper.eq(Article::getTitle, params.get("title"));
        }
        if(!StringUtils.isEmpty((String) params.get("content"))){
            wrapper.eq(Article::getContent, params.get("content"));
        }
        if(!StringUtils.isEmpty((String) params.get("type"))){
            wrapper.eq(Article::getType, params.get("type"));
        }
        if(!StringUtils.isEmpty((String) params.get("status"))){
            wrapper.eq(Article::getStatus, params.get("status"));
        }
        if(!StringUtils.isEmpty((String) params.get("tags"))){
            String[] tags = ((String) params.get("tags")).split(",");
            Arrays.sort(tags);
            wrapper.like(Article::getTags, String.join( ",",tags));
        }

        wrapper.orderByDesc(Article::getReleaseTime);
        Page<Article> pageData = articleService.page(page,wrapper);

        result.put("success",true);
        result.put("data", pageData.getRecords());
        result.put("size",pageData.getSize());
        result.put("total",pageData.getTotal());

        return result;
    }

    @PostMapping("/admin/article/add")
    public JSONObject addArticle(@RequestBody JSONObject params, HttpServletResponse response){
        JSONObject resultMap = new JSONObject();
        boolean checkPass = true;

        if( StringUtils.isEmpty( params.getString("title")) || StringUtils.isEmpty(params.getString("contentType"))  ||
                StringUtils.isEmpty(params.getString("type")) || StringUtils.isEmpty( params.getString("tags")) || StringUtils.isEmpty( params.getString("describ"))
                || ((List) params.get("tags")).isEmpty()){
            checkPass = false;
        }else if( "frame".equals( params.get("contentType") ) && StringUtils.isEmpty( params.getString("content_link"))
          || "markdown".equals( params.get("contentType") ) && StringUtils.isEmpty( params.getString("content_file"))){
            checkPass = false;
        }

        if(checkPass){
            Article article = new Article();
            List<Integer> tags = (List)params.get("tags");
            Collections.sort(tags);
            // 设置参数
            article.setTitle(params.getString("title"));
            article.setContentType(params.getString("contentType"));
            article.setType(params.getString("type"));
            article.setTags( StringUtils.join(tags,',')  );
            article.setDescrib( params.getString("describ") );
            // 设置文章内容
            if( article.getContentType().equals("frame") ){
                article.setContent(params.getString("content_link"));
            }else if( article.getContentType().equals("markdown") ){
                article.setContent(params.getString("content_file"));
            }
            article.setReleaseTime( new Timestamp(System.currentTimeMillis()));
            article.setUpdateTime( new Timestamp(System.currentTimeMillis()));
            boolean save = articleService.save(article);
            if(save){
                resultMap.put("success",true);
                resultMap.put("status",1);
                resultMap.put("info","提交成功");
            }else {
                resultMap.put("success",false);
                resultMap.put("status",0);
                resultMap.put("info","错误信息：数据库操作失败");
                response.setStatus(500);
            }
        }else {
            resultMap.put("success",false);
            resultMap.put("status",0);
            resultMap.put("info","错误信息：部分字段不和法或部分字段必要缺失");
            response.setStatus(500);
        }

        return resultMap;
    }


    @PostMapping("/admin/article/grant_on")
    public JSONObject grantOn( @RequestBody JSONObject params,HttpServletResponse response ){
        JSONObject resultMap = new JSONObject();
        List<Article> list = params.getList("list",Article.class);
        ArrayList<Article> artilceList = new ArrayList<>();
        list.forEach(item->{
            Article article = new Article();
            article.setArticleId(item.getArticleId());
            article.setStatus("1");
            artilceList.add(article);
        });

        boolean updated = articleService.updateBatchById(artilceList);
        if(updated){
            resultMap.put("success",true);
            resultMap.put("status",1);
            resultMap.put("info","操作成功");
        }else {
            resultMap.put("success",false);
            resultMap.put("status",0);
            resultMap.put("info","错误信息：数据库操作失败");
            response.setStatus(500);
        }

        return resultMap;
    }

    @PostMapping("/admin/article/grant_off")
    public JSONObject grantOff( @RequestBody JSONObject params,HttpServletResponse response ){
        JSONObject resultMap = new JSONObject();
        List<Article> list = params.getList("list",Article.class);
        ArrayList<Article> artilceList = new ArrayList<>();
        list.forEach(item->{
            Article article = new Article();
            article.setArticleId(item.getArticleId());
            article.setStatus("0");
            artilceList.add(article);
        });

        boolean updated = articleService.updateBatchById(artilceList);
        if(updated){
            resultMap.put("success",true);
            resultMap.put("status",1);
            resultMap.put("info","操作成功");
        }else {
            resultMap.put("success",false);
            resultMap.put("status",0);
            resultMap.put("info","错误信息：数据库操作失败");
            response.setStatus(500);
        }

        return resultMap;
    }

    @PostMapping("/admin/article/delete")
    public JSONObject delete( @RequestBody JSONObject params,HttpServletResponse response ){
        JSONObject resultMap = new JSONObject();
        resultMap.put("success",true);
        resultMap.put("status",1);
        resultMap.put("info","操作成功");
        List<Article> list = params.getList("list",Article.class);
        if(list.isEmpty()){
            return resultMap;
        }
        ArrayList<Article> artilceList = new ArrayList<>();
        list.forEach(item->{
            Article article = new Article();
            article.setArticleId(item.getArticleId());
            article.setStatus("0");
            artilceList.add(article);
        });

        boolean removed = articleService.removeBatchByIds(artilceList);
        if(!removed){
            resultMap.put("success",false);
            resultMap.put("status",0);
            resultMap.put("info","错误信息：数据库操作失败");
            response.setStatus(500);
        }

        return resultMap;
    }

    @PostMapping("/admin/article/update")
    public JSONObject update( @RequestBody JSONObject params,HttpServletResponse response ){
        JSONObject resultMap = new JSONObject();
        Article article = params.getObject("article", Article.class);
        resultMap.put("success",true);
        resultMap.put("status",1);
        resultMap.put("info","操作成功");
        if( article.getArticleId()==null ){
            return resultMap;
        }

        boolean update = articleService.updateById(article);
        if(!update){
            resultMap.put("success",false);
            resultMap.put("status",0);
            resultMap.put("info","错误信息：数据库操作失败");
            response.setStatus(500);
        }
        return resultMap;
    }

    @PostMapping("/admin/article/refreshCatches")
    public JSONObject refreshCaches(){
        articleCaches.scheduleCache();
        return JsonUtil.ok_info("缓存更新成功");
    }
}
